#!/usr/bin/env python

from nor_socket import Server
from threading import Thread
from time import sleep
import subprocess

class ServerWrapper(Thread):
    def __init__(self,ip,port):
        super(ServerWrapper, self).__init__()
        self.ip_ = ip
        self.port_ = port
        self.server_ = Server(ip=ip,port=port)
        # Set thread as a Daemon thread. Once all of normal thread exit,
        # Daemon thread will crash instantly without any terminate process.
        # This will cause that some resources isn't released.
        self.setDaemon(True) 

    def run(self):
        while True:
            print("waiting for a connection...")
            self.server_.accept()
            try:
                print("client connected.")
                while True:
                    requ_str = self.server_.recv()
                    if requ_str=="":
                        break
                    print("\r\n\r\nRecv from {0} > {1}".format(self.ip_,requ_str))
                    resp_str = requ_str+"--"
                    print("Send({0}:{1}) to > {2}".format(self.ip_,self.port_,resp_str))
                    self.server_.send(resp_str)
            finally:
                self.server_.close_client()



if __name__=="__main__":
	# Create two alias ip
	uut1 = "169.254.1.32"
	uut2 = "169.254.1.33"
	arm_port = 7603;
	power_port = 7604;
	dut_port = 7605;

	try:
		subprocess.call(["sudo","ifconfig","lo0","alias",uut1])
		subprocess.call(["sudo","ifconfig","lo0","alias",uut2])

		# Create two server 
		uut1_arm   = ServerWrapper(uut1,arm_port)
		uut1_power = ServerWrapper(uut1,power_port)
		uut1_dut   = ServerWrapper(uut1,dut_port)
		uut2_arm   = ServerWrapper(uut2,arm_port)
		uut2_power = ServerWrapper(uut2,power_port)
		uut2_dut   = ServerWrapper(uut2,dut_port)

		uut1_arm.start()
		uut1_power.start()
		uut1_dut.start()
		uut2_arm.start()
		uut2_power.start()
		uut2_dut.start()
		print("Launch service thread finish.")
		while True: sleep(1)
	finally:
		# Clean alias ip
		subprocess.call(["sudo","ifconfig","lo0","-alias",uut1])
		subprocess.call(["sudo","ifconfig","lo0","-alias",uut2])

